package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.bean.ResponseBean;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:TTW
 * @Discription:后台上传图片
 */
@RestController
@RequestMapping("/admin/upload")
public class UploadAction {

    /**
     * 文件上传的目录
     */
    @Value("${upload.dir}")
    private String upload;

    /**
     * 上传临时目录
     */
    @Value("${upload.tmp.dir}")
    private String tmp;

    /**
     * 文件上传到临时目录
     *
     * @return
     */
    @RequestMapping("/upload_tmp_dir")
    public ResponseBean upLoadTmpDir(MultipartFile file) throws IOException {
        if (file == null) {
            return new ResponseBean(500, "上传失败", 0);
        }
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String newFileName = System.currentTimeMillis() + extName;
        File desc = new File(tmp, newFileName);
        if (desc.exists() == false) {
            desc.mkdirs();
        }
        file.transferTo(desc);
        String[] ss = upload.split("/");
        List list = new ArrayList();
        //存储路径
        String root = ss != null && ss.length > 0 ? ss[ss.length - 1] : "";
        //图片名称
        list.add(newFileName);
        //图片路径
        list.add(( root + "/" + newFileName).replaceAll("\\\\","/"));

        return new ResponseBean(200, "", list);
    }

    /**
     * 确定好图片,文件移动
     *
     * @param fileName 文件的名称
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public ResponseBean upLoadDir(String fileName) throws IOException {
        if (fileName == null || fileName.trim().length() == 0) {
            return new ResponseBean(500, "文件位置修改失败", "error");
        }

        File desc = new File(upload);
        if (desc.exists() == false) {
            desc.mkdirs();
        }
        boolean b = UploadAction.copyFile(tmp + "/" + fileName, upload, fileName);
        return new ResponseBean(b ? 200 : 500, "", b);
    }

    /**
     * 文件复制
     *
     * @param srcPath  要复制文件路径
     * @param destPath 复制到那里
     * @param fileName 复制来的文件的名称
     * @return 是否成功
     * @throws IOException
     */
    private static boolean copyFile(String srcPath, String destPath, String fileName) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(srcPath);
            if (!file.exists()) {
                return false;
            }
            is = new FileInputStream(file);
            os = new FileOutputStream(new File(destPath, fileName));
            byte[] b = new byte[1024];
            int len = 0;
            while (-1 != (len = is.read(b))) {
                os.write(b, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            return false;
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }
        return true;
    }

    @PostMapping("/uploadimg")
    @CrossOrigin("*")
    public ResponseBean upload(MultipartFile  file) throws IllegalStateException, IOException
    {
        //目的地1 商品图片
        File uploadFile = new File(upload+"images/goods");
        if (uploadFile.exists()==false){
            uploadFile.mkdirs();
        }
        //目的地2  类别图片
        File typeFile = new File(upload+"goodsType");
        if (typeFile.exists()==false){
            typeFile.mkdirs();
        }
        //目的地4  轮播图图片
        File lunbotu = new File(upload+"lunbotu");
        if (lunbotu.exists()==false){
            lunbotu.mkdirs();
        }
        File advertise = new File(upload+"advertise");
        if (advertise.exists()==false){
            advertise.mkdirs();
        }
        //目的地
        File tmpFile = new File(tmp);
        if (tmpFile.exists()==false){
            tmpFile.mkdirs();
        }

        //得到旧的文件名
        String oldFileName = file.getOriginalFilename();
        //得到原来的后辍名
        int index = oldFileName.lastIndexOf('.');
        int index2=-10;
        if(index<0)
            index2=file.getContentType().lastIndexOf('/');
        String extName="";
        if(index>-1)
            extName = oldFileName.substring(index);
        if(index2>-1)
            extName="."+file.getContentType().substring(index2+1);
        //根据系统时间拼一个当前新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //目的地
        File descFile = new File(tmp, newFileName);
        file.transferTo(descFile);

        return new ResponseBean(0, "上传成功", newFileName);
    }

    @PostMapping("/sendimg")
    @CrossOrigin("*")
    public ResponseBean sendimg(MultipartFile  file) throws IllegalStateException, IOException
    {
        //目的地1 商品图片
        File uploadFile = new File(upload+"chat");
        if (uploadFile.exists()==false){
            uploadFile.mkdirs();
        }

        //得到旧的文件名
        String oldFileName = file.getOriginalFilename();
        //得到原来的后辍名
        int index = oldFileName.lastIndexOf('.');
        int index2=-10;
        if(index<0)
            index2=file.getContentType().lastIndexOf('/');
        String extName="";
        if(index>-1)
            extName = oldFileName.substring(index);
        if(index2>-1)
            extName="."+file.getContentType().substring(index2+1);
        //根据系统时间拼一个当前新的文件名
        String newFileName = System.currentTimeMillis()+extName;
        //目的地
        File descFile = new File(upload+"chat", newFileName);
        file.transferTo(descFile);

        return new ResponseBean(0, "上传成功", newFileName);
    }

    //上传视频的接口
    @RequestMapping(value = "/uploadVideo",method = RequestMethod.POST)
    public Object uploadVideo(@RequestParam("layuiVideo") MultipartFile[] layuiFile, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> map2=new HashMap<>();
        map =kitFileUtil(layuiFile, request, response);
        String error = map.get("error").toString();
        if("101".equals(error)){
            map2.put("error",101);
            map2.put("message",map.get("message"));
            return map;
        }
        map2.put("error",0);
        String url[]=(String[])map.get("url");
        map2.put("url",url[0]);
        return JSONObject.toJSON(map2);
    }

    private static ServletContext servletContext;

    //视频上传的工具方法
    public Map<String,Object> kitFileUtil(@RequestParam("imgFile") MultipartFile[] imgFile, HttpServletRequest request, HttpServletResponse response){

                 // 文件保存目录路径
                 String savePath = upload+"video/";

                 //文件保存目录URL
                 String saveUrl  = "upload/video/";

                 //定义允许上传的文件扩展名
                 HashMap<String, String> extMap = new HashMap<String, String>();
                 extMap.put("image", "gif,jpg,jpeg,png,bmp");
                 extMap.put("flash", "swf,flv");
                 extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
                 extMap.put("file", "doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2");

                 //最大文件大小
                 long maxSize = 9000000;

                 response.setContentType("text/html; charset=UTF-8");

                 if(!ServletFileUpload.isMultipartContent(request)){
                         return getError("请选择文件。");
                     }
                 //检查目录
                 File uploadDir = new File(savePath);
                 if(!uploadDir.exists()){
                         uploadDir.mkdir();
             //            return getError("上传目录不存在。");
                     }

                 //检查目录写权限
                 if(!uploadDir.canWrite()){
                         return getError("上传目录没有写权限。");
                     }

                 String dirName = request.getParameter("dir");
                 if (dirName == null) {
                         dirName = "image";
                     }
                 if(!extMap.containsKey(dirName)){
                         return getError("目录名不正确。");
                     }

                 //创建文件夹
                 savePath += dirName + "/";
                 saveUrl += dirName + "/";
                 File saveDirFile = new File(savePath);
                 if (!saveDirFile.exists()) {
                         saveDirFile.mkdirs();
                     }
                 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                 String ymd = sdf.format(new Date());
                 savePath += ymd + "/";
                 saveUrl += ymd + "/";
                 File dirFile = new File(savePath);
                 if (!dirFile.exists()) {
                         dirFile.mkdirs();
                     }
                 String url[] = new String[imgFile.length];
                 Map<String,Object> map = new HashMap<String, Object>();
                 for (int i=0;i<imgFile.length;i++) {
                         // 获取上传文件的名字
                         String fileName = imgFile[i].getOriginalFilename();
                         // 获取长度
                         long fileSize = imgFile[i].getSize();

                         if(!imgFile[i].isEmpty()){

                                 // 检查文件大小
                                 if(imgFile[i].getSize() > maxSize){
                                         return getError("上传文件大小超过限制。");
                                     }

                                 // 检查扩展名
                                 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                                 if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
                                         return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                                     }

                                 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                                 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                                 try{
                                         // 保存文件
                                         FileCopyUtils.copy(imgFile[i].getInputStream(), new FileOutputStream(savePath + newFileName));

                                     }catch(Exception e){
                                         return getError("上传文件失败。");
                                     }
                                 url[i] = saveUrl + newFileName;
            }
                     }
                 map.put("error", 0);
                 map.put("url", url);
                 return map;
             }

             private Map<String,Object> getError(String message) {
                 Map<String,Object> map = new HashMap<String, Object>();
                 map.put("error", 101);
                map.put("message", message);
                 return map;
             }
}
